package com.contactsconverter.utils;

import java.io.Serializable;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.contactsconverter.activity.CTEventActivity;
import com.contactsconverter.volley.CTRequestQueue;
import com.contactsconverter.R;
import com.difsonapps.contacttranslator.dto.EventDTO;

public class CTEventUtil {

	Context context;
	
	public CTEventUtil(Context context)
	{
		this.context= context;
	}
	public void onGetEvent(){
		
		String DEFAULT_SERVER_URL = context.getResources().getString(R.string.default_server_url);
		String SERVICE_AUTH_URL = "rest/event/notification/lastid/%s";
		String notificationId = CTUtils.getPreference(CTUtils.NOTIFICATION_ID, context);
	    long lastId = CTUtils.stringToLong(notificationId);
	    //bouchonner
		String url = String.format(DEFAULT_SERVER_URL+SERVICE_AUTH_URL, String.valueOf(lastId));

		JsonArrayRequest jsObjRequest = new JsonArrayRequest
		(url, new Response.Listener<JSONArray>() {

			@Override
			public void onResponse(JSONArray jsonObject) {
				try {		
					onGetEventSuccess(jsonObject);					
				} catch (JSONException e) {

					e.printStackTrace();
				}

			}		    
		}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				onGetEventFail(error);
			}
		});

		CTRequestQueue.getInstance(context.getApplicationContext()).addToRequestQueue(jsObjRequest);
	}
	private void onGetEventSuccess(JSONArray eventArray) throws JSONException{

		
		Log.e("DIFSON ", "onGetEventSuccess "+eventArray);
				
		ArrayList<EventDTO> listEventDTO = new ArrayList<EventDTO>();
		
		if(eventArray==null || eventArray.length()<=0)
		{
			
			return;
		}
		int maxId=0;
		
	
		
		for (int i = 0; i<eventArray.length(); i++) {
		
		
			JSONObject jsonObject = (JSONObject)eventArray.get(i);
			EventDTO eventDTO  = new EventDTO();
		
			eventDTO.setContent(jsonObject.getString("content"));
			
		
			
			eventDTO.setIcon(jsonObject.getInt("icon"));
			
			
			eventDTO.setId(jsonObject.getInt("id"));
			
			eventDTO.setMessage(jsonObject.getString("message"));
		
			eventDTO.setTitle(jsonObject.getString("title"));
			eventDTO.setUrl(jsonObject.getString("url"));
		
			
			if(eventDTO.getId()>maxId)
				maxId = eventDTO.getId();
			
			listEventDTO.add(eventDTO);
		}
		
		notification(listEventDTO, maxId);
		
	
	}
	
	public void notification(ArrayList<EventDTO> listEventDTO,int maxId)
	{
		

		Log.e("DIFSON", "notification maxid : "+maxId);
		NotificationCompat.Builder mBuilder =
		        new NotificationCompat.Builder(context)
		        .setSmallIcon(R.drawable.event)
		        .setContentTitle("Contact Converter Notification Line")
		        .setContentText("De nouvelles notifications sont disponible sur la 'Notification Line'!");
	
		
		/*Drawable dwb = context.getResources().getDrawable(eventDTO.getIcon());
		if(dwb!=null)
		{
			mBuilder.setSmallIcon(eventDTO.getIcon());
		}*/
			
		Intent resultIntent = new Intent(context, CTEventActivity.class);
		
		Log.e("RAS ", listEventDTO.toString());
		resultIntent.putExtra(CTUtils.EVENT_LIST, (Serializable)listEventDTO);
		
		TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
		stackBuilder.addParentStack(CTEventActivity.class);
		stackBuilder.addNextIntent(resultIntent);
		PendingIntent resultPendingIntent =
		        stackBuilder.getPendingIntent(
		            0,
		            PendingIntent.FLAG_UPDATE_CURRENT
		        );
		mBuilder.setContentIntent(resultPendingIntent);
		NotificationManager mNotificationManager =
		    (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		// mId allows you to update the notification later on.
		
		CTUtils.savePreference(CTUtils.NOTIFICATION_ID, String.valueOf(maxId), context);
		
		Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
		mBuilder.setSound(alarmSound);
				
		mNotificationManager.notify(maxId, mBuilder.build());
	}


	private void onGetEventFail(VolleyError error){
		Log.e("DIFSON ", "Error onGetEventFail"+error);
		return;
	}

	
}
